package com.collectplus.express.passport;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.app.AppCaptureActivity;
import com.collectplus.express.app.Intents;
import com.collectplus.express.evaluate.EvaluateActivity;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.BoxcodeModel;
import com.collectplus.express.model.ParcelBillBean;
import com.collectplus.express.model.PassportDetailBean;
import com.collectplus.express.model.ShareBean;
import com.collectplus.express.parcel.ParcelDetailActivity;
import com.collectplus.express.parcel.ParcelDigitalBillActivity;
import com.collectplus.express.tools.DensityUtils;

import droid.frame.ui.dialog.BaseDialog;
import droid.frame.umeng.UMeng;
import droid.frame.utils.Android;
import droid.frame.utils.android.Log;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.JsonParser;
import droid.frame.utils.lang.Str;

/**
 * passport详情页 TODO layout种字体的默认颜色是 app_font_2 ??? 为啥
 *
 * @author coffee <br>
 *         2016-10-5下午7:49:34
 */
@Deprecated
public class PassportDetailsDialogActivity extends BaseActivity2 implements View.OnClickListener {

    private int[] backColors = {R.drawable.passport_corners_top_1, // 上门(标准+有袋)
            R.drawable.passport_corners_top_2, // 到柜
            R.drawable.passport_corners_top_3};// 到驿站

    // 顶部椭圆背景layout
    private ViewGroup mTopLayout;

    private PassportDetailBean item;
    //
    private BaseDialog mShareDialog;

    /**
     * 智能柜
     */
    // private PassportBoxCodeInc boxCodeInc;

    /**
     * 驿站路由操作viewstub
     */
    private PassportStationRouteOperate routeOperate;

    /**
     * 只能柜路由操作viewstub
     */
    private PassportBoxRouteOperate boxRouteOperate;

    private static PassportDetailsDialogActivity instance;

    @Override
    @SuppressLint({"ResourceAsColor", "MissingSuperCall"})
    protected void onCreate(Bundle savedInstanceState) {
        instance = this;
        // 第二个方法在此参数无效
        overridePendingTransition(R.anim.in_bottom2top, 0);
        super.onCreate(savedInstanceState);
        Window win = getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        // win.getDecorView().setMinimumWidth((int) (win.getWindowManager().getDefaultDisplay().getWidth() * 0.6));// 设置dialog的宽度
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // lp.horizontalMargin = 300;
        lp.gravity = Gravity.CENTER;
        win.setAttributes(lp);
        String parcelId = getIntent().getStringExtra("parcelId");
        item = (PassportDetailBean) getIntent().getSerializableExtra("item");
        // 不是传过来的bean,调用接口获取数据
        if (item == null) {
            if (!Str.isEmpty(parcelId)) {
                showLoadingDialog("");
                //                AppHttp.getInstance().getPassportDetail(parcelId);
                // updateData(item);
            } else {
                showToast("数据错误");
                finish();
            }
        } else {
            if (item != null) {
                updateData(item);
            }
        }
        UMeng.click(getContext(), "goto_passport_click");
    }

    public void findViewById() {
        setContentView(R.layout.passport_details_new);
        // 寄件码
        // boxCodeInc = new PassportBoxCodeInc(this);
        routeOperate = new PassportStationRouteOperate(this, R.id.passport_multiple_operate_item);
        boxRouteOperate = new PassportBoxRouteOperate(this, R.id.passport_box_operate_item);
        //
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //
            case R.id.passport_express_number:
                UMeng.click(getContext(), "passport_cpoy_express_number_click");
                if (item != null && !Str.isEmpty(item.getExpressNumber())) {
                    Android.copyToClipboard(item.getExpressNumber());
                    showToast("复制成功");
                } else {
                    showToast("当前没有运单号");
                }
                break;
            // 路由状态点击
            // 导航
            case R.id.passport_nav:
                UMeng.click(getContext(), "passport_navication_click");
                // Intents.navigation(item.getLatitude(), item.getLongitude(), null, null);
                Intents.navigation(item.getLatitude() + "", item.getLongitude() + "", //
                        item.getGdLatitude(), item.getGdLongitude(), item.getStationAddress());
                break;
            // 路由状态点击
            case R.id.passport_state:
                // 查看物流
                if (item.getPassportStatus() == 3) {
                    Intent intent = new Intent(PassportDetailsDialogActivity.this, ParcelDetailActivity.class);
                    intent.putExtra("parcelStatus", item.getParcelStatus());
                    intent.putExtra("parcelId", item.getParcelId());
                    intent.putExtra("from", 1);
                    getContext().startActivity(intent);
                    // 服务评论
                } else if (item.getPassportStatus() == 4) {
                    Intent intent = new Intent(PassportDetailsDialogActivity.this, EvaluateActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("orderId", item.getOrderId());
                    intent.putExtras(bundle);
                    getContext().startActivity(intent);
                }
                break;
            // 服务保障
            case R.id.passport_share:
                // new WXshare(getActivityContext()).sendTimelines("title", "desc");
                //			showLoadingDialog(null);
                //			AppHttp.getInstance().weiXinShare(item.getOrderId() + "");
                UMeng.click(getContext(), "passport_share_get_stamp_click");
                //                showToast("活动已结束");
                Intent intent1 = new Intent(getContext(), WebViewActivity.class);
                intent1.putExtra("title", "服务保障");
                startActivity(intent1);
                break;
            // 联系客服
            case R.id.passport_contact_service:
                UMeng.click(getContext(), "passport_kefu_click");
                DialogMgr.showPhoneDialog(getContext(), null);
                break;
            // 跳转包电子面单
            case R.id.parcel_bill:
                // Intent intent = new Intent();
                // intent.setClass(getContext(), ParcelDigitalBillActivity.class);
                // intent.putExtra("orderId", item.getOrderId());
                // getContext().startActivity(intent);
                UMeng.click(getContext(), "passport_parcel_bill_click");
                if (item != null) {
                    showLoadingDialog("");
                    AppHttp.getInstance().getParcelBill(item.getOrderId());
                }
                break;
            case R.id.scan_view:
                Intent intent = new Intent();
                intent.setClass(getContext(), AppCaptureActivity.class);
                intent.setAction(Intents.capture_station);
                // fragment.startActivityForResult(intent, 101);
                startActivity(intent);
                break;
            //揽收超时，用短信的方式通知火箭侠
            case R.id.passport_route_outtime_message:
                if (item != null) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().sendOuttimeMessage(item.getParcelId());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 电子面单
            case MsgID.passport_box_code:
                AppResult<BoxcodeModel> codeResult = JSON.parser(msg.obj, BoxcodeModel.class);
                if (codeResult.isSuccess()) {
                    final BoxcodeModel codeBean = codeResult.getResult();
                    if (codeBean != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                boxRouteOperate.setNewCode(codeBean);
                            }
                        });
                    }
                } else {
                    showToast(codeResult.getMessage());
                }
                return false;
            //点击电子面单返回数据
            case MsgID.parcel_bill:
                cancelLoadingDialog();
                AppResult<ParcelBillBean> biLLResult = JSON.parser(msg.obj, ParcelBillBean.class);
                if (biLLResult.isSuccess()) {
                    final ParcelBillBean billBean = biLLResult.getResult();
                    if (billBean != null && item != null) {
                        Intent intent = new Intent(this, ParcelDigitalBillActivity.class);
                        intent.putExtra("parcelStatus", item.getParcelStatus());
                        intent.putExtra("parcelBill", billBean);
                        intent.putExtra("parcelId", item.getParcelId());
                        startActivity(intent);
                    }
                } else {
                    showToast(biLLResult.getMessage());
                }
                return true;
            //parcel详情返回
            case MsgID.passport_detail:
                cancelLoadingDialog();
                AppResult<PassportDetailBean> parcelResult = JSON.parser(msg.obj, PassportDetailBean.class);
                final PassportDetailBean parcelDetail = parcelResult.getResult();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (parcelDetail != null) {
                            parcelDetail.setParcelStatus(1);
                            item = parcelDetail;
                            updateData(parcelDetail);
                        } else {
                            showToast("获取数据失败");
                        }
                    }
                });
                return false;
            // 取消订单以后直接关闭passport详情页面
            case MsgID.order_cancel:
                finish();
                return false;
            // 微信分享
            case MsgID.weixin_share:
                cancelLoadingDialog();
                final ShareBean share = JsonParser.parse(msg.obj + "", ShareBean.class);
                // 默认的
                if (share == null) {
                    showToast("获取分享数据失败");
                    return true;
                } else {
                    Bitmap picBitmap = BitmapUtils.loadBitmapFromNet(share.getPicUrl());
                    share.setPicBitmap(picBitmap);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mShareDialog = DialogMgr.showWeixinShare((BaseActivity2) getContext(), share, item.getOrderId());
                    }
                });
                return false;
            // 微信分享回调以后、取消对话框
            case MsgID.weixin_share_close:
                if (mShareDialog != null) {
                    mShareDialog.cancel();
                }
                return false;
            //待揽收超时发送
            case MsgID.send_out_time_message:
                cancelLoadingDialog();
                final AppResult<?> result = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            showToast("已通知，火箭侠将以火箭般的速度前往揽收");
                        } else {
                            showToast(result.getMessage());
                        }

                    }
                });
                return true;
        }
        return super.handleMessage(msg);
    }

    public void updateData(PassportDetailBean item) {
        mTopLayout = (ViewGroup) findViewById(R.id.passport_top_layout);

        findViewById(R.id.parcel_bill).setOnClickListener(this);
        findViewById(R.id.scan_view).setOnClickListener(this);

        // 联系客服
        findViewById(R.id.passport_contact_service).setOnClickListener(this);
        // 服务保障
        findViewById(R.id.passport_share).setOnClickListener(this);
        // 设置包裹的图片
        ImageView mReceiveExpress = (ImageView) findViewById(R.id.passport_goods_image);
        if (!Str.isEmpty(item.getParcelImgUrl())) {
            AppLogic.getInstance().loadImage(item.getParcelImgUrl(), mReceiveExpress);
        }

        handleTopBackgroup(mTopLayout);
        handleReceiverInfo();// 处理收件人信息
        handleExressInfo();// 处理快递公司信息
        // 驿站
        if (item.getIsStation()) {
            handleStationInfo();
            // 有操作的路由信息
            if (item.getPassportStatus() == 0 || item.getPassportStatus() == 1 || item.getPassportStatus() == 4 || item.getPassportStatus() == 5) {
                // boxCodeInc.loadLayout(item);
                routeOperate.loadLayout(item);
                findViewById(R.id.passport_route_item).setVisibility(View.GONE);
            } else {
                // 处理无操作路由 (没有查看路由，评价操作)
                handleRouteState();
            }
        } else if (item.getIsBox()) {
            // 隐藏驿站信息
            findViewById(R.id.passport_station_layout).setVisibility(View.GONE);
            if (item.getPassportStatus() == 1 || item.getPassportStatus() == 4 || item.getPassportStatus() == 5) {
                boxRouteOperate.loadLayout(item);
                // 隐藏不带操作的路由信息
                findViewById(R.id.passport_route_item).setVisibility(View.GONE);
            } else {
                // 处理无操作路由
                handleRouteState();
            }
        }

    }

    // 处理收件人信息
    private void handleReceiverInfo() {
        TextView orderTime = (TextView) findViewById(R.id.passport_order_time);
        orderTime.setText(droid.frame.utils.sqlite.DateUtils.format(item.getOrderTime()));
        // 投递袋编码
        TextView bagCode = (TextView) findViewById(R.id.passport_bagcode);
        if (TextUtils.isEmpty(item.getBagCode())) {
            //			((ViewGroup) bagCode.getParent()).setVisibility(View.GONE);
            bagCode.setText(getString(R.string.parcel_nobag_code));
        } else {
            bagCode.setText(item.getBagCode());
            Str.formatBagCode(bagCode);
        }
        // 地址前面的icon
        ImageView addressIcon = (ImageView) findViewById(R.id.service_point_logo);
        if (item.getIsBox()) {
            addressIcon.setImageResource(R.drawable.service_point_icon);
        } else if (item.getIsStation()) {
            addressIcon.setImageResource(R.drawable.service_station_icon);
        } else {
            addressIcon.setImageResource(R.drawable.icon_location);
        }
        // 收件人地址
        TextView address = (TextView) findViewById(R.id.passport_addr);
        if (item.getIsBox() || item.getIsStation()) {
            // 有袋自助
            address.setText(item.getStationAddress());
            // 导航
            View nav = findViewById(R.id.passport_nav);
            ((ViewGroup) nav.getParent()).setVisibility(View.VISIBLE);
            nav.setOnClickListener(this);
            findViewById(R.id.passport_nav_line).setVisibility(View.VISIBLE);
        } else {
            address.setText(item.getStationAddress());
            View nav = findViewById(R.id.passport_nav);
            ((ViewGroup) nav.getParent()).setVisibility(View.GONE);
            nav.setOnClickListener(null);// 上门不需要导航
            findViewById(R.id.passport_nav_line).setVisibility(View.GONE);
        }
        address.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                TextView tv = (TextView) v;
                Android.copyToClipboard(tv.getText().toString());
                showToast("复制成功");
                return false;
            }
        });
        TextView label = (TextView) findViewById(R.id.passport_people_label);
        TextView receiverName = (TextView) findViewById(R.id.passport_people);
        label.setText(item.getReceiverCity());
        receiverName.setText(item.getReceiverName());
        if (item.getIsStation()) {
            label.setTextColor(getResources().getColor(R.color.app_fontcolor_333333));
            receiverName.setTextColor(getResources().getColor(R.color.app_fontcolor_333333));
        } else {
            label.setTextColor(getResources().getColor(R.color.white));
            receiverName.setTextColor(getResources().getColor(R.color.white));
        }
    }

    /**
     * 顶部背景
     *
     * @param view
     */
    public void handleTopBackgroup(View view) {
        ImageView logoIV = (ImageView) findViewById(R.id.passport_logo);
        int left = view.getPaddingLeft();
        int top = view.getPaddingTop();
        int right = view.getPaddingRight();
        int bottom = view.getPaddingBottom();
        if (item.getIsBox()) {
            logoIV.setImageResource(R.drawable.passport_top_logo_white);
            // top背景颜色 根据包裹类型判断
            view.setBackgroundResource(backColors[1]);
            view.setPadding(left, top, right, bottom);
        } else if (item.getIsStation()) {
            logoIV.setImageResource(R.drawable.passport_top_logo_black);
            // top背景颜色 根据包裹类型判断
            view.setBackgroundResource(backColors[2]);
            view.setPadding(left, top, right, bottom);
        } else {// 标准
            // view.setBackgroundResource(backColors[0]);
            // view.setPadding(left, top, right, bottom);
        }
    }

    /**
     * 处理快递公司信息
     */
    private void handleExressInfo() {
        TextView name = (TextView) findViewById(R.id.passport_express);
        TextView expressNumber = (TextView) findViewById(R.id.passport_express_number);
        expressNumber.setOnClickListener(this);
        if (!Str.isEmpty(item.getExpressCompanyName())) {
            name.setText(item.getExpressCompanyName());
        }
        if (!Str.isEmpty(item.getExpressNumber())) {
            expressNumber.setText(item.getExpressNumber());
        }
    }

    /**
     * 驿站信息
     */
    private void handleStationInfo() {
        findViewById(R.id.passport_station_layout).setVisibility(View.VISIBLE);
        TextView name = (TextView) findViewById(R.id.passport_station_name);
        TextView serviceTime = (TextView) findViewById(R.id.passport_station_serviceTime);
        name.setText(item.getStationName());
        if (!isEmpty(item.getStationServiceTime())) {
            serviceTime.setText("营业时间: " + item.getStationServiceTime());
        }
        findViewById(R.id.passport_station_call).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                UMeng.click(getContext(), "passport_call_station_phone_click");
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + item.getStationPhone()));
                getContext().startActivity(intent);
            }
        });
    }

    /**
     * 处理路由
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void handleRouteState() {
        // 状态文本
        TextView statusText = (TextView) findViewById(R.id.passport_state);
        // 状态点击事件
        statusText.setOnClickListener(this);
        TextView routeInformation = (TextView) findViewById(R.id.passport_route);
        TextView routeOuttimeMessagemation = (TextView) findViewById(R.id.passport_route_outtime_message);
        routeOuttimeMessagemation.setOnClickListener(this);
        if (item.getIsStation()) {
            routeInformation.setText(item.getStatusDesc());
            if (item.getPassportStatus() == 1) {
                setParcelProgressBar(2, 0, 0, 0, 0);
                statusText.setText("查看物流");
            } else if (item.getPassportStatus() == 2) {
                setParcelProgressBar(2, 2, 0, 0, 0);
                statusText.setText("待揽收");
                if (isNotEmpty(item.getPickOutTime())) {
                    routeOuttimeMessagemation.setVisibility(View.VISIBLE);
                    routeOuttimeMessagemation.setText(item.getPickOutTime());
                } else {
                    routeOuttimeMessagemation.setVisibility(View.INVISIBLE);
                }
            } else if (item.getPassportStatus() == 3) {
                setParcelProgressBar(2, 2, 2, 0, 0);
                statusText.setText("待交接");
            } else if (item.getPassportStatus() == 4) {
                setParcelProgressBar(2, 2, 2, 2, 0);
                statusText.setText("服务评价");
            } else if (item.getPassportStatus() == 5) {
                setParcelProgressBar(2, 2, 2, 2, 2);
                statusText.setText("服务评价");
            }
        } else if (item.getIsBox()) {
            // 到柜重新设置margintop
            LinearLayout.LayoutParams layoutParams = (LayoutParams) statusText.getLayoutParams();
            int top = DensityUtils.dip2px(getContext(), 104);
            layoutParams.setMargins(layoutParams.leftMargin, top, layoutParams.rightMargin, layoutParams.bottomMargin);
            // 到柜重新设置marginBottom
            LinearLayout.LayoutParams layoutParams2 = (LayoutParams) routeInformation.getLayoutParams();
            layoutParams2.setMargins(layoutParams2.leftMargin, layoutParams2.topMargin, layoutParams2.rightMargin, top);
            routeInformation.setText(item.getStatusDesc());
            if (item.getPassportStatus() == 1) {
                setParcelProgressBar(1, 0, 0, 0, 0);
                statusText.setText("查看物流");
            } else if (item.getPassportStatus() == 2) {
                setParcelProgressBar(1, 1, 0, 0, 0);
                statusText.setText("待揽收");
                if (isNotEmpty(item.getPickOutTime())) {
                    routeOuttimeMessagemation.setText(item.getPickOutTime());
                    routeOuttimeMessagemation.setVisibility(View.VISIBLE);
                } else {
                    routeOuttimeMessagemation.setVisibility(View.INVISIBLE);
                }
            } else if (item.getPassportStatus() == 3) {
                setParcelProgressBar(1, 1, 1, 0, 0);
                statusText.setText("待交接");
            } else if (item.getPassportStatus() == 4) {
                setParcelProgressBar(1, 1, 1, 1, 0);
                statusText.setText("服务评价");
            } else if (item.getPassportStatus() == 5) {
                setParcelProgressBar(1, 1, 1, 1, 1);
                statusText.setText("服务评价");
            }
        }
    }

    /**
     * 物流状态条颜色
     *
     * @param colors 1柜子,2驿站
     */
    @SuppressWarnings("deprecation")
    private void setParcelProgressBar(int... colors) {
        ImageView item1 = (ImageView) findViewById(R.id.passport_progress_1);
        ImageView item2 = (ImageView) findViewById(R.id.passport_progress_2);
        ImageView item3 = (ImageView) findViewById(R.id.passport_progress_3);
        ImageView item4 = (ImageView) findViewById(R.id.passport_progress_4);
        ImageView item5 = (ImageView) findViewById(R.id.passport_progress_5);

        GradientShape shape1 = new GradientShape(getContext());
        GradientShape shape2 = new GradientShape(getContext());
        GradientShape shape3 = new GradientShape(getContext());
        GradientShape shape4 = new GradientShape(getContext());
        GradientShape shape5 = new GradientShape(getContext());

        shape1.setStyle(0, colors[0]);
        shape2.setStyle(1, colors[1]);
        shape3.setStyle(1, colors[2]);
        shape4.setStyle(1, colors[3]);
        shape5.setStyle(2, colors[4]);
        if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
            item1.setBackground(shape1);
            item2.setBackground(shape2);
            item3.setBackground(shape3);
            item4.setBackground(shape4);
            item5.setBackground(shape5);
        } else {
            item1.setBackgroundDrawable(shape1);
            item2.setBackgroundDrawable(shape2);
            item3.setBackgroundDrawable(shape3);
            item4.setBackgroundDrawable(shape4);
            item5.setBackgroundDrawable(shape5);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //从评价页面返回，评论成功后返回
        if (requestCode == 1001) {
            Log.d("11111", "评论成功后销毁");
            finish();
        }
    }

    public static PassportDetailsDialogActivity getInstance() {
        return instance;
    }

    @Override
    public void finish() {
        super.finish();
        // if (boxCodeInc != null) {
        // boxCodeInc.onDestroy();
        // }
        if (routeOperate != null) {
            routeOperate.onDestroy();
        }
        overridePendingTransition(0, R.anim.out_top2bottom);
    }

    @Override
    protected void onDestroy() {
        instance = null;
        super.onDestroy();
    }
}
